package com.zmn.oms.api.controller;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.oms.common.constant.FacadeTrackConsts;
import com.zmn.oms.model.entity.log.FacadeTrackLog;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.daowei.DaoweiConsts;
import com.zmn.oms.third.dj58.DaoJia58Consts;
import com.zmn.oms.third.jingdong.JingdongConsts;
import com.zmn.oms.third.tc58.Tc58Consts;
import com.zmn.oms.zmn.business.interfaces.log.FacadeTrackLogBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * @author huangyifeng
 * @Description
 * @date 2020/5/9 19:01
 */
@RestController
@RequestMapping("/test/chan")
@Slf4j
public class TestController {

    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private FacadeTrackLogBService facadeTrackLogBService;

    /**
     * 支持跟踪记录的渠道
     */
    private Map<String, Boolean> channelFilter = new HashMap<>();
    {
        Map<String, Boolean> filter = channelFilter;
        // 到位系列
        filter.put(String.valueOf(DaoweiConsts.CHANNEL_ID_APP), Boolean.TRUE);
        filter.put(String.valueOf(DaoweiConsts.CHANNEL_ID_DTW), Boolean.TRUE);
        filter.put(String.valueOf(DaoweiConsts.CHANNEL_ID_KYX), Boolean.TRUE);
        filter.put(String.valueOf(DaoweiConsts.CHANNEL_ID_ZX), Boolean.TRUE);
        // 58同城系列
        filter.put(String.valueOf(Tc58Consts.CHANNEL_ID_VIP), Boolean.TRUE);
        filter.put(String.valueOf(Tc58Consts.CHANNEL_ID_FWK), Boolean.TRUE);
        filter.put(String.valueOf(Tc58Consts.CHANNEL_ID_JX), Boolean.TRUE);
        filter.put(String.valueOf(Tc58Consts.CHANNEL_ID_JX_PIPE), Boolean.TRUE);
        filter.put(String.valueOf(Tc58Consts.CHANNEL_ID_JX_CLOCK), Boolean.TRUE);
        // 京东服务+
        filter.put(String.valueOf(JingdongConsts.CHANNEL_ID), Boolean.TRUE);
        // 58到家系列（直约，同城公寓，58到家返修单）
        filter.put(String.valueOf(DaoJia58Consts.CHANNEL_ID_API), Boolean.TRUE);
        filter.put(String.valueOf(DaoJia58Consts.CHANNEL_ID_APARTMENT), Boolean.TRUE);
        filter.put(String.valueOf(DaoJia58Consts.CHANNEL_ID_DJ58_REWORK), Boolean.TRUE);
    }


    /**
     * 根据用户手机号匹配用户信息
     *
     * @param orderId
     * @return
     */
    @RequestMapping("/msg")
    public void getUserInfo(Long orderId, String stackTrace, HttpServletResponse response) {
        log.info("[订单消息记录查询] receive request: orderId=[{}], containsStackTrace=[{}]", orderId, stackTrace);


        PrintWriter writer = null;
        String utf8 = "UTF-8";
        response.setCharacterEncoding(utf8);
        response.setContentType("application/json;charset=UTF-8");

        try {
            writer = response.getWriter();
            writer.write(String.format("订单号:%s\r\n", orderId));
            writer.write("查询时间:" + DateUtil.getNowFormatted() + "\r\n");

            List<FacadeTrackLog> facadeTrackLogs = Optional.ofNullable(orderId)
                    .map(id -> orderWorkService.findOrderWorkByKey(id, id))
                    .map(orderWork -> channelFilter.get(String.valueOf(orderWork.getChannelId())))
                    .map(value -> facadeTrackLogBService.listByOrderId(orderId))
                    .orElse(Collections.EMPTY_LIST);

            if (facadeTrackLogs == null || facadeTrackLogs.isEmpty()) {
                writer.write("没有消息数据！\r\n");
            }
            else {
                writer.write("\r\n******************* 消  息  轨  迹 " + "*******************************************\r\n\r\n");
                for (int i=facadeTrackLogs.size()-1; i>=0; i--) {
                    FacadeTrackLog item = facadeTrackLogs.get(i);

                    writer.write("  时间: " + DateUtil.toString(DateUtil.parse(String.valueOf(item.getBeginTime()), "yyyyMMddHHmmssSSS")) + "\r\n");
                    writer.write(Objects.equals(FacadeTrackConsts.DATA_IN, item.getType()) ? "  Msg ==>>【ZMN】\r\n\r\n" : "  【ZMN】==>> Msg\r\n\r\n");
                    writer.write("  备注: " + item.getRemark() + "\r\n\r\n");
                    writer.write("  结果: " + (Objects.equals(GlobalConsts.YES, item.getSuccess()) ? "成功" : "失败") + "\r\n");
                    writer.write("  错误信息: " + item.getErrorMsg() + "\r\n");
                    writer.write("  请求摘要: " + item.getReqSummary() + "\r\n");
                    writer.write("  响应摘要: " + item.getRespSummary() + "\r\n");

                    if (Objects.equals(GlobalConsts.YES, item.getError())) {
                        writer.write("  异常中断: 是\r\n");
                    }
                    if (item.getErrorStackTrace() != null && "true".equals(stackTrace)) {
                        writer.write("  堆栈信息: "+ item.getErrorStackTrace() +"\r\n");
                    }
                    writer.write("\r\n==============================================================================\r\n\r\n\r\n");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.flush();
        writer.close();

        log.info("[订单消息记录查询] query complete: orderId=[{}], containsStackTrace=[{}]", orderId, stackTrace);
    }
}
